package com.ahuan.utils;

import com.ahuan.domain.Module;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

public class TreeBuilder1<T> {

    private final List<T> items;
    private final String idFieldName;
    private final String parentIdFieldName;
    private final String childrenFieldName;

    public TreeBuilder1(List<T> items, String idFieldName, String parentIdFieldName, String childrenFieldName) {
        this.items = items;
        this.idFieldName = idFieldName;
        this.parentIdFieldName = parentIdFieldName;
        this.childrenFieldName = childrenFieldName;
    }

    public List<T> buildTree(Object parentId) {
        List<T> children = new ArrayList<>();
        for (T item : items) {
            try {
                Field idField = item.getClass().getDeclaredField(idFieldName);
                idField.setAccessible(true);
                Object itemId = idField.get(item);

                Field parentIdField = item.getClass().getDeclaredField(parentIdFieldName);
                parentIdField.setAccessible(true);
                Object itemParentId = parentIdField.get(item);

                if (itemParentId != null && itemParentId.equals(parentId)) {
                    Field childrenField = item.getClass().getDeclaredField(childrenFieldName);
                    childrenField.setAccessible(true);

                    List<T> subChildren = buildTree(itemId);
                    childrenField.set(item, subChildren);

                    children.add(item);
                }
            } catch (NoSuchFieldException | IllegalAccessException e) {
                e.printStackTrace();
            }
        }
        return children;
    }



    public static void main(String[] args) {
        List<Module> nodes = new ArrayList<>();
        nodes.add(new Module("1", "0", "结点1",true,true,null)); // 根节点
        nodes.add(new Module("2", "1", "结点2",true,true,null)); // 节点1的子节点
        nodes.add(new Module("3", "1", "结点3",true,true,null)); // 节点1的子节点
        nodes.add(new Module("4", "2", "结点4",true,true,null)); // 节点2的子节点
        nodes.add(new Module("5", "0", "结点5",true,true,null)); // 节点2的子节点

        TreeBuilder1<Module> treeBuilder = new TreeBuilder1(nodes,"id","pId","children");
        List<Module> tree = treeBuilder.buildTree("0"); // 传入根节点的 ID，这里假设根节点的 parentId 为 0
//        printTree(tree, 0);
        System.out.println(tree);
    }

    public static void printTree(List<Module> nodes, int depth) {
        for (Module node : nodes) {
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < depth; i++) {
                sb.append("  "); // 用空格表示层级关系
            }
            sb.append(node.getName());
            System.out.println(sb.toString());
//            printTree(node.getChildren(), depth + 1);
        }
    }
}
